package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"week1/midd"
	"week1/server/model/mysql"
	"week1/server/request"
)

// 添加方法
func CreateUser(c *gin.Context) {
	//实例化模型
	var user request.CreateUserRequest
	//验证器
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	err := mysql.CreateUser(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": "-1",
			"msg":  "服务器错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "0",
		"msg":  "添加成功",
	})
}

func GetUserList(c *gin.Context) {
	//实例化模型
	var user request.GetUserListRequest
	//验证器
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	list, err := mysql.GetUserList(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": "-1",
			"msg":  "服务器错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "0",
		"msg":  "列表展示",
		"data": list,
	})

}

// 修改用户信息 （编辑）

func UpdateUserInfo(c *gin.Context) {
	//实例化模型
	var user request.UpdateUserInfo
	//验证器
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	err := mysql.UpdateUserInfo(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": "-1",
			"msg":  "服务器错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "0",
		"msg":  "更新成功",
	})
}

// 删除用户信息

func DeleteUserInfo(c *gin.Context) {
	//实例化模型
	var user request.DeleteUserInfo
	//验证器
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//调用中间件 里面的判断 判断用户状态
	midd.UserIsStatus(user)
	if user.Status == 1 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": "-55",
			"msg":  "用户状态已启动禁止删除",
		})
		return
	}

	err := mysql.DeleteUserInfo(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": "-1",
			"msg":  "服务器错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "0",
		"msg":  "删除成功",
	})
}
